package com.shensi.common.core.interceptor;

import com.alibaba.fastjson.JSON;
import com.shensi.common.core.constant.GlobalConstant;
import com.shensi.common.core.constant.ServiceContext;
import com.shensi.common.core.constant.ServiceContextHolder;
import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author mao
 */
@Configuration
@Slf4j
public class FeignClientsInterceptor implements RequestInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(FeignClientsInterceptor.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                //新请求会导致长度改变，过滤
                if ("content-length".equalsIgnoreCase(name)) {
                    continue;
                }
                //防止传递格式修改，过滤
                if ("accept-encoding".equalsIgnoreCase(name)) {
                    continue;
                }
                String value = request.getHeader(name);
                requestTemplate.header(name, value);
            }
        }
        if (null != SecurityUtils.getAuthentication() && null != SecurityUtils.getAuthentication().getPrincipal()) {
            Object principal = SecurityUtils.getAuthentication().getPrincipal();
            if (principal instanceof LoginUser) {
                requestTemplate.header(GlobalConstant.HEADER_KEY_USER_INFO, JSON.toJSONString(principal));
            }
        }
        ServiceContext serviceContext = ServiceContextHolder.getContext();
        requestTemplate.header(GlobalConstant.HEADER_KEY_REQUEST_ID, serviceContext.getRequestId());
        logger.info("GlobalFeignRequestInterceptor:Url:{}, header:{}", requestTemplate.url(), requestTemplate.request().headers());
    }
}
